
package com.newasia.server.common.exception;

import com.newasia.server.common.result.ManagementRetCode;
import com.newasia.server.common.result.ResponseData;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;

public class ExceptionUtil {

    /**
     * 将下层抛出的异常转换为resp返回码
     *
     * @param e Exception
     * @return
     */
    public static ResponseData handlerException4biz(ResponseData response, Exception e){
        Exception ex = null;
        if (!(e instanceof Exception)) {
            return null;
        }
        if (e instanceof ValidateException) {
            response.setCode(((ValidateException) e).getErrorCode());
            response.setMessage(e.getMessage());
        }else if(e instanceof ProcessException) {
            response.setCode(((ProcessException) e).getErrorCode());
            response.setMessage(e.getMessage());
        }else if(e instanceof BizException) {
            response.setCode(((BizException) e).getErrorCode());
            response.setMessage(e.getMessage());
        }else if (e instanceof Exception) {
            response.setCode(ManagementRetCode.SYSTEM_ERROR.getCode());
            response.setMessage(ManagementRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }

    /**
     * 将下层抛出的异常转换为resp返回码
     *
     * @param e Exception
     * @return
     */
    public static ResponseData handlerExceptionShiro(ResponseData response, Exception e){
        Exception ex = null;
        if (!(e instanceof Exception)) {
            return null;
        }
        if (e instanceof IncorrectCredentialsException) {
            response.setCode(ManagementRetCode.USERORPASSWORD_ERRROR.getCode());
            response.setMessage(ManagementRetCode.USERORPASSWORD_ERRROR.getMessage());
        }else if(e instanceof LockedAccountException) {
            response.setCode(ManagementRetCode.USERORPASSWORD_ERRROR.getCode());
            response.setMessage(ManagementRetCode.USERORPASSWORD_ERRROR.getMessage());
        }else if(e instanceof AuthenticationException) {
            response.setCode(ManagementRetCode.USERNAME_NOT_EXIST.getCode());
            response.setMessage(ManagementRetCode.USERNAME_NOT_EXIST.getMessage());
        }else if(e instanceof WeChatLoginException) {
            response.setResult(((WeChatLoginException) e).getToken());
            response.setCode(((WeChatLoginException) e).getErrorCode());
            response.setMessage(e.getMessage());
        }else if (e instanceof Exception) {
            response.setCode(ManagementRetCode.SYSTEM_ERROR.getCode());
            response.setMessage(ManagementRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }
}
